import sys
import os
from loguru import logger

Config = {
    "log": {
        "path": "/tmp/log",
        "prefix": "xxx",
        "method": "both",  # screen 屏幕, log 日志, both 屏幕+日志
    }
}


def log_init(config):
    log_method = config["log"]["method"]
    screen_log = False
    log_file = False

    if log_method == "both":
        screen_log = True
        log_file = True
    elif log_method == "screen":
        screen_log = True
    elif log_method == "log":
        log_file = True
    else:
        raise ValueError("未知的日志模式 log_method")

    if screen_log:
        logger.remove(0)
        log_format = (
            "<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> |"
            "<level>{level: <5}</level> |"
            "<cyan>{function}:{line}</cyan>- <level>{message}</level>"
        )
        logger.add(sys.stderr, format=log_format, enqueue=True, colorize=True)
    else:
        logger.remove(0)

    if log_file:
        log_path = config["log"]["path"]
        log_prefix = config["log"]["prefix"]
        os.makedirs(log_path, exist_ok=True)
        log_format = "[{time:YYYYMMDD-HH:mm:ss.S} {level}] {message}"
        logger.add(
            "%s/%s_{time}.log" % (log_path, log_prefix),
            format=log_format,
            rotation="1000 KB",
            retention=3,
            compression="gz",
            enqueue=True,
            buffering=8192,
        )


log_init(Config)
logger.info("hello world")
